package Oberflaeche;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Client{
			
			
	JPanel mainPanel;
	JScrollPane qScroller;
	JScrollPane qScrollerChat;
	String sName;
	
	JTextArea incoming, chat;
    JTextField outgoing, chatField;
    BufferedReader reader;
    PrintWriter writer;
    Socket sock;
    String[] messageSplit;
    boolean stapelKarteAufgedeckt;
    String[] spielerName = new String[3];
    JButton sendButton = new JButton("add Player");
    JButton stapelButton = new JButton("Stapel : ");
    JButton reihe1Button = new JButton("Reihe1" );
    JButton reihe2Button = new JButton("Reihe2");
    JButton reihe3Button = new JButton("Reihe3");
    JButton chatButton = new JButton("sende Nachricht");
     
    public void go() {

//    	JXLoginPane peo = new JXLoginPane();
 //   	peo.setMessage("satan :(");
  //  	peo.setVisible(true);
    	
    	
    	stapelButton.setPreferredSize(new Dimension(120,30));
    	reihe1Button.setPreferredSize(new Dimension(120,30));
    	reihe2Button.setPreferredSize(new Dimension(120,30));
    	reihe3Button.setPreferredSize(new Dimension(120,30));
    	stapelButton.setVisible(false);
    	reihe1Button.setVisible(false);
    	reihe2Button.setVisible(false);
    	reihe3Button.setVisible(false);
    	chatButton.setVisible(false);

    	
    	JFrame frame = new JFrame("Coloretto");
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    	
    	mainPanel = new JPanel();
        incoming = new JTextArea(9, 50);
        incoming.setLineWrap(true);
        incoming.setWrapStyleWord(true);
        incoming.setEditable(false);
        
        chat = new JTextArea(9, 50);
        chat.setLineWrap(true);
        chat.setWrapStyleWord(true);
        chat.setEditable(false);
        
        qScroller = new JScrollPane(incoming);
        qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        qScrollerChat = new JScrollPane(chat);
        qScrollerChat.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        qScrollerChat.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
       
        outgoing = new JTextField(20);
        chatField = new JTextField(20);
        
        sendButton.addActionListener(new SendButtonListener());
        stapelButton.addActionListener(new StapelButtonListener());
        reihe1Button.addActionListener(new Reihe1ButtonListener());
        reihe2Button.addActionListener(new Reihe2ButtonListener());
        reihe3Button.addActionListener(new Reihe3ButtonListener());
        chatButton.addActionListener(new chatButtonListener());
        
        
        mainPanel.add(qScroller);
        
        mainPanel.add(outgoing);
        mainPanel.add(sendButton);
        mainPanel.add(stapelButton);
        mainPanel.add(reihe1Button);
        mainPanel.add(reihe2Button);
        mainPanel.add(reihe3Button);
       
        mainPanel.add(chat);
        mainPanel.add(chatField);
        mainPanel.add(chatButton);
        
        frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        setUpNetworking();
        
        Thread readerThread = new Thread(new IncomingReader());
        readerThread.start();
        
        frame.setSize(650, 500);
        frame.setVisible(true);
        qScroller.setVisible(false);
        chatField.setVisible(false);
        chat.setVisible(false);

    	String name = String.valueOf(Math.random());
    	outgoing.setText(name);    	
    	outgoing.requestFocus();

    
    	frame.addWindowListener(new WindowAdapter() {
    		public void windowClosed(WindowEvent e){
    			try {
					sock.close();
	    			reader.close();
	    			
				} catch (IOException e1) {
					e1.printStackTrace();
				}
    		}
    		
		});

    }
    
    private void setUpNetworking() {
        try {
            sock = new Socket("127.0.0.1", 5000);
            InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(streamReader);
            writer = new PrintWriter(sock.getOutputStream());
            System.out.println("networking established");
        }
        catch(IOException ex)
        {try{
        	sock.close();} catch(Exception e){}
//            ex.printStackTrace();
        }
    }
    
    public class SendButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            try {
                writer.println("newPlayer "+ outgoing.getText().replace(" ", "_"));
                writer.flush();
                sName= outgoing.getText().replace(" ", "_"); 
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
            sendButton.setVisible(false);
            outgoing.setVisible(false);
            qScroller.setVisible(true);
            incoming.append(sName + "\n\n");
            incoming.append("Waiting for other players"); 
        	chatButton.setVisible(true);
        	chatField.setVisible(true);
        	chat.setVisible(true);
        }
    }
    
    public class StapelButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            try {
            	writer.println("s");
                writer.flush();  
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }
    
    public class Reihe1ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            try {
                if (stapelKarteAufgedeckt)
            		writer.println("a0");
            	else 
            		writer.println("r0");
                writer.flush();
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }
    
    public class Reihe2ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            try {
                
            	if (stapelKarteAufgedeckt)
            		writer.println("a1");
            	else 
            		writer.println("r1");
                writer.flush();
                
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }
    
    public class Reihe3ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            try {
                
            	if (stapelKarteAufgedeckt)
            		writer.println("a2");
            	else 
            		writer.println("r2");
                writer.flush();
                
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }
    
    public class chatButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            try {
                writer.println("chat " + chatField.getText());
                writer.flush();
                
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            chatField.setText("");
            chatField.requestFocus();
            
        }
    }
    
    
    
    public static void main(String[] args) {
        new Client().go();
    }
    
    class IncomingReader implements Runnable {
        public void run() {
            String message;
            try {
                while ((message = reader.readLine()) != null) { 
                	stapelButton.setVisible(true);
                    reihe1Button.setVisible(true);
                    reihe2Button.setVisible(true);
                    reihe3Button.setVisible(true);
                    chat.setVisible(true);
                    chatButton.setVisible(true);
                    chatField.setVisible(true);
                	
                	messageSplit = message.split(" ");
                	
                	if(messageSplit[0].equals("chat")){
                		
                		chat.append(message.substring(5) + "\n");
                		System.out.println("chat: " + message.substring(5) + "\n");
                	}
                	
                	
                	else {
	                	if(messageSplit[17].equals("0"))
	                		stapelKarteAufgedeckt = false;
	                	else
	                		stapelKarteAufgedeckt = true;
	                	
	                	System.out.println("spielzug " + message);
	                    incoming.setText("");
	                    
	                    spielerName[0] = messageSplit[2];
	                    spielerName[1] = messageSplit[5];
	                    spielerName[2] = messageSplit[8];
	                    incoming.append(sName + "\n\n");
	                    
	                    int spielerIndex; //welcher index habe ich
	                    
	                    if (sName.equals(spielerName[0]))
	                    	spielerIndex = 0; 
	                    else if (sName.equals(spielerName[1]))
	                    	spielerIndex = 1;
	                    else
	                    	spielerIndex = 2;
	                    
	                    if(messageSplit[0].equals("1"))
	                    	if (messageSplit[3].equals("0")&&messageSplit[6].equals("0")&&messageSplit[9].equals("0"))
	                    		incoming.append("Spiel vorbei \n\n");
	                    	else
	                    		incoming.append("Letzte Runde \n\n");
	                    
	                   incoming.append( (messageSplit[3].equals("1")?(messageSplit[1].equals("0")?"=>":""):"x ") + messageSplit[2] + ":\t "+ messageSplit[4] + "\n"); // Spieler 1 Name und Karten
	                    incoming.append( (messageSplit[6].equals("1")?(messageSplit[1].equals("1")?"=>":""):"x ") + messageSplit[5] + ":\t "+ messageSplit[7] + "\n"); // Spieler 2 Name und Karten
	                    incoming.append( (messageSplit[9].equals("1")?(messageSplit[1].equals("2")?"=>":""):"x ") + messageSplit[8] + ":\t "+ messageSplit[10] + "\n"); // Spieler 3 Name und Karten
	                   
	                    // Reihe 1
	                    if(messageSplit[11].equals("1")){
	                    	reihe1Button.setVisible(true);
	                    	reihe1Button.setEnabled(true);
	                    	
	                    	if((messageSplit[12].equals("0") && messageSplit[17].equals("0")) || (messageSplit[12].length()>=3 && !(messageSplit[17].equals("0"))))
	                    		reihe1Button.setEnabled(false);
	                    		reihe1Button.setText("Reihe 1:\t "+ (messageSplit[12].equals("0")?" ":messageSplit[12]) + "\n"); // Reihe 1 Karten
	                    	} else	
	                    	reihe1Button.setVisible(false);
	                    
	                    // Reihe 2
	                    if(messageSplit[13].equals("1")){
	                    	reihe2Button.setEnabled(true);
	                    	reihe2Button.setVisible(true);
	                    	
	                    	if((messageSplit[14].equals("0") && messageSplit[17].equals("0")) || (messageSplit[14].length()>=3 && !(messageSplit[17].equals("0"))))
	                    		reihe2Button.setEnabled(false);
	                    		reihe2Button.setText("Reihe 2:\t "+ (messageSplit[14].equals("0")?" ":messageSplit[14]) + "\n"); // Reihe 2 Karten
	                    } else  	
	                    	reihe2Button.setVisible(false);
	                    
	                    // Reihe 3
	                    if(messageSplit[15].equals("1")){
	                    	reihe3Button.setEnabled(true);
	                    	reihe3Button.setVisible(true);
	                    	
	                    	if((messageSplit[16].equals("0") && messageSplit[17].equals("0"))||(messageSplit[16].length()>=3 && !(messageSplit[17].equals("0"))))
	                    		reihe3Button.setEnabled(false);
	                    		reihe3Button.setText("Reihe 3:\t "+ (messageSplit[16].equals("0")?" ":messageSplit[16]) + "\n\n"); // Reihe 3 Karten
	                    } else 
	                    	reihe3Button.setVisible(false);
	                    	
	                    //Stappel
	                   if(!(messageSplit[17].equals("0"))){
	                    	stapelButton.setText("Stapel: "+ messageSplit[17]); // Vom Stapel aufgedeckt
	                    	stapelButton.setEnabled(false);
	                    }else {
	                    	stapelButton.setEnabled(true);
	                    	stapelButton.setText("Stapel:  ");
	                    }
	                    
	                    if (((messageSplit[11].equals("1") && messageSplit[12].length()>=3)||messageSplit[11].equals("0"))    &&   ((messageSplit[13].equals("1")&&messageSplit[14].length()>=3)||messageSplit[13].equals("0"))    &&((messageSplit[15].equals("1")&&messageSplit[16].length()>=3)||messageSplit[15].equals("0"))){
	                    	stapelButton.setEnabled(false);
	                    }
	                    
	                    if(messageSplit[0].equals("1")&&messageSplit[11].equals("0")&&messageSplit[13].equals("0")&&messageSplit[15].equals("0"))
	                    	stapelButton.setVisible(false);
	                    
	                    if((spielerIndex != Integer.parseInt(messageSplit[1]))){
	                    	stapelButton.setEnabled(false);
	                    	reihe1Button.setEnabled(false);
	                    	reihe2Button.setEnabled(false);
	                    	reihe3Button.setEnabled(false);	
	                    }
                	}
                }
            } catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }
}